<template>
	<div class="shell">
		<!-- 主登录表单 -->
		<div class="login-card">
			<!-- 头部 -->
			<div class="login-header">
				<img src="../../assets/柚子.png" alt="logo" class="logo">
				<h1 class="title">紫槿云柚校园服务登录</h1>
			</div>
			<!-- 表单 -->
			<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @submit.prevent="handleLogin" label-position="top">
				<el-form-item label="学号" prop="account">
					<el-input v-model="loginForm.account" placeholder="请输入学号" size="large" clearable :prefix-icon="User"/>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="loginForm.password" type="password" placeholder="请输入密码" size="large" show-password clearable :prefix-icon="Lock"/>
				</el-form-item>
				<el-form-item class="login-btn-item">
					<el-button type="primary" size="large" @click="handleLogin" class="login-btn" :loading="loginLoading">登录</el-button>
				</el-form-item>
			</el-form>
			<!-- 尾部 -->
			<div class="form-footer">
				<el-button type="text" @click="showForgotPasswordModal = true" :icon="Connection">忘记密码？</el-button>
			</div>
		</div>
		<!-- 忘记密码弹窗 -->
		<el-dialog v-model="showForgotPasswordModal" title="重置密码" width="450px" class="forgot-password-dialog" :before-close="clearForgetPasswordFrom">
			<!-- 表单区域 -->
			<el-form ref="forgotPasswordFormRef" :model="forgotPasswordForm" :rules="forgotPasswordRules" label-position="top">
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="forgotPasswordForm.email" placeholder="请输入绑定邮箱" size="large" clearable :prefix-icon="Message"/>
				</el-form-item>
				<el-form-item label="验证码" prop="verificationCode">
					<div class="verification-group">
						<el-input v-model="forgotPasswordForm.verificationCode" placeholder="请输入验证码" size="large" :prefix-icon="ChatDotRound"/>
						<el-button type="primary" @click="sendVerificationCode" :disabled="isVerificationSent && countdown > 0" class="verification-btn">
							{{ isVerificationSent && countdown > 0 ? `重新发送(${countdown}s)` : '发送验证码' }}
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="新密码" prop="newPassword">
					<el-input v-model="forgotPasswordForm.newPassword" type="password" placeholder="请输入新密码" size="large" show-password :prefix-icon="Lock"/>
				</el-form-item>
				<el-form-item label="确认密码" prop="newPassword">
					<el-input v-model="forgotPasswordForm.confirmPassword" type="password" placeholder="请确认新密码" size="large" show-password :prefix-icon="Lock"/>
				</el-form-item>
			</el-form>
			<!-- 功能区 -->
			<template #footer>
		        <span class="dialog-footer">
			        <el-button type="primary" @click="handleForgotPassword" :loading="resetPasswordLoading">确认修改</el-button>
			        <el-button @click="showForgotPasswordModal = false">取消</el-button>
		        </span>
			</template>
		</el-dialog>
	</div>
</template>


<script setup lang="ts">
import {ref, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {User, Lock, Message, ChatDotRound, Connection} from '@element-plus/icons-vue'
import * as LoginAPI from './index.ts'

/**响应式数据*/
// 登录表单引用
const loginFormRef = ref();
// 登录加载状态
const loginLoading = ref(false)
// 重置密码加载状态
const resetPasswordLoading = ref(false)
// 忘记密码表单引用
const forgotPasswordFormRef = ref()
// 忘记密码弹窗显示状态
const showForgotPasswordModal = ref(false)
// 忘记密码表单引用
const isVerificationSent = ref(false)
// 倒计时
const countdown = ref(0)
/**表单数据*/
// 登录表单数据
let loginForm = reactive<LoginAPI.LoginForm>({
	account: '',
	password: ''
})
// 忘记密码表单数据
let forgotPasswordForm = reactive<LoginAPI.ForgotPasswordForm>({
	email: '',
	verificationCode: '',
	newPassword: '',
	confirmPassword: ''
})
/**表单验证规则*/
// 登录表单验证规则
const loginRules = reactive({
	account: [
		{required: true, message: '请输入学号', trigger: 'blur'},
		{pattern: /^\d{8,12}$/, message: '学号格式不正确', trigger: 'blur'}
	],
	password: [
		{required: true, message: '请输入密码', trigger: 'blur'},
		{min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
	]
})
// 忘记密码表单验证规则
const forgotPasswordRules = reactive({
	email: [
		{required: true, message: '请输入邮箱', trigger: 'blur'},
		{type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
	],
	verificationCode: [
		{required: true, message: '请输入验证码', trigger: 'blur'},
		{pattern: /^\d{6}$/, message: '验证码必须为6位数字', trigger: 'blur'}
	],
	newPassword: [
		{required: true, message: '请输入新密码', trigger: 'blur'},
		{min: 8, message: '密码长度不能少于8位', trigger: 'blur'},
		{
			pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).*$/,
			message: '密码必须包含大小写字母、数字和特殊字符',
			trigger: 'blur'
		}
	]
})
/**方法*/
// 登录功能实现
const handleLogin = async () =>
{
	// 如果表单引用不存在则直接返回
	if (!loginFormRef.value)
	{
		return
	}
	try
	{
		// 验证表单数据是否符合规则
		const valid = await loginFormRef.value.validate()
		if (valid)
		{
			// 设置登录加载状态为true，显示加载动画
			loginLoading.value = true
			// 登录请求API调用
			let token = LoginAPI.login(loginForm);
			console.log(token)
			localStorage.setItem('token', await token)
			// 登录成功提示
			ElMessage.success(`登录成功！欢迎 ${loginForm.account} 同学`)
		}
	}
	catch (error)
	{
		// 表单验证失败或登录异常处理
		ElMessage.error('请填写完整的登录信息')
	}
	finally
	{
		// 无论登录成功与否，都要关闭加载状态
		loginLoading.value = false
	}
}
// 发送验证码
const sendVerificationCode = () =>
{
	// 验证邮箱
	if (!forgotPasswordForm.email)
	{
		ElMessage.error('请输入邮箱地址')
		return
	}
	// 发送验证码
	LoginAPI.sendVerificationCode(forgotPasswordForm.email)
		 .then(result =>
		 {
			 // 验证成功
			 if (result)
			 {
				 // 设置已发送验证码状态为true
				 isVerificationSent.value = true
				 countdown.value = 60
				 // 倒计时
				 const timer = setInterval(() =>
				 {
					 countdown.value--
					 if (countdown.value <= 0)
					 {
						 clearInterval(timer)
					 }
				 }, 1000)
				 ElMessage.success(`验证码已发送到: ${forgotPasswordForm.email}`)
			 }
		 })
		 .catch(() =>
		 {
			 // 验证失败
			 ElMessage.error('邮箱地址有误')
		 })
}
// 修改密码
const handleForgotPassword = async () =>
{
	// 如果表单引用不存在则直接返回
	if (!forgotPasswordFormRef.value)
	{
		return
	}
	try
	{
		const valid = await forgotPasswordFormRef.value.validate()
		if (valid)
		{
			resetPasswordLoading.value = true
			// 模拟修改密码请求
			await new Promise(resolve => setTimeout(resolve, 1500))
			ElMessage.success('密码修改成功！')
			showForgotPasswordModal.value = false
			// 重置表单
			clearForgetPasswordFrom()
			isVerificationSent.value = false
		}
	}
	catch (error)
	{
		ElMessage.error('请填写完整的信息')
	}
	finally
	{
		resetPasswordLoading.value = false
	}
}
// 清空忘记密码弹出框表单
const clearForgetPasswordFrom = () =>
{
	forgotPasswordForm = {
		email: '',
		verificationCode: '',
		newPassword: '',
		confirmPassword: ''
	}
}
</script>


<style>
/*总布局*/
.shell {
	display: flex;
	justify-content: center;
	align-items: center;
	background: linear-gradient(135deg, #e0f7fa 0%, #c8e6c9 100%);
	height: 100vh;
}

/*登录卡片*/
.login-card {
	width: 500px;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 16px;
	box-shadow: 0 20px 15px rgba(0, 0, 0, 0.1);
	padding: 30px;
	position: relative;
	overflow: hidden;
}

/*登录卡片头条*/
.login-card::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 5px;
	background: linear-gradient(90deg, #4caf50, #8bc34a);
}

/*表单头部*/
.login-header {
	text-align: center;
	margin-bottom: 30px;
}

/*logo*/
.logo {
	width: 80px;
	height: 80px;
	margin-bottom: 10px;
}

/*标题*/
.title {
	color: #2e7d32;
	font-size: 28px;
	margin-bottom: 8px;
	font-weight: 600;
}

/*登录按钮*/
.login-btn {
	width: 100%;
	background-color: #4caf50;
	border-color: #4caf50;
}

.login-btn:hover {
	background-color: #388e3c;
	border-color: #388e3c;
}

/*表单尾部*/
.form-footer {
	text-align: center;
	margin-top: 20px;
}

/*忘记密码按钮*/
.form-footer .el-button--text {
	color: #66bb6a;
}

.form-footer .el-button--text:hover {
	color: #2e7d32;
}

/* 验证码组 */
.verification-group {
	display: flex;
	gap: 20px;
	align-items: center;
	width: 100%;
	justify-content: space-between;
}

/* 验证码输入框 */
.verification-group .el-input {
	width: 65%;
}

/* 验证码按钮 */
.verification-group .el-button {
	height: 40px;
}

/* 弹窗样式 */
.forgot-password-dialog .el-dialog {
	border-radius: 16px;
}

.forgot-password-dialog .el-dialog__header {
	border-bottom: 1px solid #e0e0e0;
	padding: 15px 20px 10px;
}

.forgot-password-dialog .el-dialog__title {
	color: #2e7d32;
	font-weight: 600;
}

/* Element Plus 组件样式覆盖 */
.el-button--primary {
	background-color: #4caf50;
	border-color: #4caf50;
}

.el-button--primary:hover {
	background-color: #388e3c;
	border-color: #388e3c;
}

.el-button--text {
	color: #66bb6a;
}

.el-button--text:hover {
	color: #2e7d32;
}

.el-form-item__label {
	color: #388e3c !important;
	font-weight: 500;
}
</style>